<template>
  <div id="maps"></div>
</template>

<script>
export default {
  props: ["datas", "name"],
  mounted() {
    this.inData();
  },
  methods: {
    inData() {
      var map, districtTask, popupDOM;
      let data = this.datas;
      let name = this.name;
console.log(name,data);
      // let res = axios.get("https://apis.map.qq.com/ws/geocoder/v1/", {
      //   address: e.name,
      //   key: "DG4BZ-WXAE2-KFVUR-CI7UQ-Q4P7Q-B2FBX"
      // })
      // 申请的key和sn
      //   SGMap.tokenTask
      //     .login("你申请的appKey", "你申请的appSecret")
      //     .then(function () {
      //       initMap();
      //     });
      // SGMap.tokenTask
      //   .login(
      //     "46a7d2bc47e23f9f83d6317b362ec8c5",
      //     "c0670e180c653f1b974e40f61ad1a7ca"
      //   )
      //   .then(() => {
      //     // 加载地图
      //     initMap();
      //   });

      SGMap.tokenTask
        .login(
          "46a7d2bc47e23f9f83d6317b362ec8c5",
          "c0670e180c653f1b974e40f61ad1a7ca"
        )
        .then(function () {
          SGMap.plugin("SGMap.DistrictTask").then(function (res) {
            districtTask = new SGMap.DistrictTask();
            initMap();
          });
        });

      function initMap() {
        map = new SGMap.Map({
          // 地图绑定的DOM元素ID
          container: "maps",
          // 地图样式
          style: "aegis://styles/aegis/Streets",
          // 默认缩放层级
          zoom: 6,
          maxZoom: 11,
          minZoom: 4,
          // 地图中心点
          center: data, //经纬度
          // 地图默认字体
          localIdeographFontFamily: "Microsoft YoHei",
          // interactive:false     如果设置为false，地图交互操作停止，包括鼠标、键盘等交互将停止响应
        });

        map.addControl(
          new SGMap.GeolocateControl({
            showCompass: true,
          }),
          "bottom-right"
        );
        map.addControl(
          new SGMap.ScaleControl({
            maxWidth: 80,
            unit: "metric",
          }),
          "bottom-left"
        );
        // var bounds = map.getBounds();
        // console.log(bounds);
        var bounds = {
          _ne: { lng: 118.5377544548532, lat: 32.55622782533946 },
          _sw: { lng: 115.78979913258729, lat: 31.52837042318022 },
        };
        console.log(bounds);
        //   map.setMaxBounds(
        //  bounds
        //   );
        map.on("load", function (e) {
          // console.log(e);
          // 初始化Popup
          popupDOM = new SGMap.Popup({
            // 是否显示关闭按钮
            // closeButton: false,
            closeOnClick: false,
            offset: {
              bottom: [0, -40],
            },
          });
          popupDOM
            .setLngLat([116.397428, 39.90923])
            .setHTML("<di>1111111</div>")
            .addTo(map);
          // 行政区划面
          map.addLayer({
            id: "power-polygon",
            type: "fill",
            source: {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: [],
              },
            },
            paint: {
              "fill-color": "white",
              "fill-opacity": 0.8,
            },
          });
          //行政区划边界线
          map.addLayer({
            id: "power-line",
            type: "line",
            source: {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: [],
              },
            },
            paint: {
              "line-color": "green",
              "line-width": 2,
            },
          });

          //遮罩面
          map.addLayer({
            id: "mask-polygon",
            type: "fill",
            source: {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: [],
              },
            },
            paint: {
              "fill-color": "white",
              "fill-opacity": 0.8,
              "fill-outline-color": "white",
            },
          });

          //面标注
          map.addLayer({
            id: "power-polygen-symbol",
            type: "symbol",
            source: {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: [],
              },
            },
            layout: {
              "text-font": ["Microsoft YaHei Regular"],
              "text-field": "{name}",
              "text-size": 26,
            },
            // paint: {
            //   "text-color": "black",
            // },
          });

          // 行政区划名称查询行政区划
          districtTask
            .searchDistrict({
              keyword: name,
              // 建议直辖市取2，其他省份取1，提升请求速度
              subdistrict: 2,
              extension: true,
            })
            .then(function (result) {
              var features = [],
                featuresSymbol = [],
                featuresPolygon = [],
                // 外层遮罩方形边界
                outSideShape = [
                  // [
                  //   [129.08605140490641, 46.53186534100985],
                  //   [109.08605140490641, 20.931139019287684],
                  //   [123.33266999835769, 20.931139019287684],
                  //   [123.33266999835769, 46.53186534100985],
                  //   [109.08605140490641, 46.53186534100985],
                  // ],
                  // [
                  //   [48.27, 135.05],
                  //   [39.15, 73.33],
                  //   [53.33, 123.15],
                  //   [3.51, 112.16],
                  //   // [0, 0],
                  // ],
                ],
                // 主要区分直辖市和其他省份
                district =
                  result.data.districts[0].sub_districts.length == 1
                    ? result.data.districts[0].sub_districts[0]
                    : result.data.districts[0];

              // 限制最大显示范围，也可以初始化地图的时候用maxZoom设置一个最大展示层级
              // map.setMaxBounds(['200','200','200','200']);
              // console.log(parseInt(district.bbox));
              /**
               * 根据行政区划服务数据，调整数据结构，目的是构建对应单面和混合面的数组层级。
               * 三维数组，单面geometry结构：
               * 四维数组，geometry: {
                    type: "Polygon",
                    coordinates: [
                      [
                        [lng, lat],
                        ...
                      ],
                    ],
                  }
               * 混合多面geometry结构：
               * geometry: {
                  type: "MultiPolygon",
                  coordinates: [
                    [
                      [
                        [lng, lat],
                        ...
                      ]
                      ...
                    ],
                    ...
                  ],
                }
               * 
              */
              for (var o in district.sub_districts) {
                if (district.sub_districts[o].shape == undefined) continue;
                var shape = district.sub_districts[o].shape;
                var shapeMultiPolygon = [];

                // 标注
                featuresSymbol.push({
                  type: "Feature",
                  geometry: {
                    coordinates: district.sub_districts[o].center
                      .split(",")
                      .map(Number),
                    type: "Point",
                  },
                  properties: {
                    name: district.sub_districts[o].name,
                  },
                });
                // 边界
                if (shape.type == "MultiPolygon") {
                  for (var o in shape.coordinates) {
                    if (shape.coordinates[o] instanceof Array) {
                      features = features.concat(shape.coordinates[o]);
                    }
                  }
                } else {
                  features.push(shape.coordinates[0]);
                }
              }
              // 面数据和遮罩
              if (district.shape.type == "MultiPolygon") {
                //    console.log(district.shape.coordinates)
                for (var o in district.shape.coordinates) {
                  // outSideShape = outSideShape.concat(
                  //   district.shape.coordinates[o]
                  // );
                  featuresPolygon = featuresPolygon.concat([
                    district.shape.coordinates[o],
                  ]);
                }
              } else {
                // outSideShape = outSideShape.concat(
                //   district.shape.coordinates
                // );
                featuresPolygon = featuresPolygon.concat(
                  district.shape.coordinates
                );
              }
              // 更新视图
              // 遮罩
              map.getSource("mask-polygon").setData({
                type: "FeatureCollection",
                features: [
                  {
                    type: "Feature",
                    geometry: {
                      type: "MultiPolygon",
                      coordinates: [outSideShape],
                    },
                  },
                ],
              });

              // 行政区划面
              map.getSource("power-polygon").setData({
                type: "FeatureCollection",
                features: [
                  {
                    type: "Feature",
                    geometry: {
                      type: district.shape.type,
                      coordinates: featuresPolygon,
                    },
                  },
                ],
              });

              // 行政区划边界
              map.getSource("power-line").setData({
                type: "FeatureCollection",
                features: [
                  {
                    type: "Feature",
                    geometry: {
                      type: "MultiLineString",
                      coordinates: features,
                    },
                  },
                ],
              });

              //面标注数据
              map.getSource("power-polygen-symbol").setData({
                type: "FeatureCollection",
                features: featuresSymbol,
              });
            });
        });
      }
    },
  },
};
</script>

<style>
#maps {
  margin-left: 178px;
  /* border: 1px solid red; */
  height: 883px;
  width: 2001px;
}
</style>
